package com.lkz.ribbon.controller;

import com.lkz.ribbon.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponents;
import org.springframework.web.util.UriComponentsBuilder;

import java.net.URI;
import java.util.HashMap;
import java.util.Map;

@RestController
public class ConsumerController {

    @Autowired
    RestTemplate restTemplate ;


    /**************** getForEntity系列方法 ******************/
    @RequestMapping(value = "/ribbon-consumer", method = RequestMethod.GET)
    public String helloConsumer(){
        return restTemplate.getForEntity("http://HELLO-SERVICE/hello", String.class).getBody() ;
    }

    @RequestMapping(value = "/ribbon-user", method = RequestMethod.GET)
    @ResponseBody
    public String ribbonUser(){
        return restTemplate.getForEntity("http://HELLO-SERVICE/user?name={1}", String.class, "liukaizhao").getBody() ;
    }

    @RequestMapping(value = "/ribbon-username", method = RequestMethod.GET)
    @ResponseBody
    public String ribbonUserName(){
        User user = restTemplate.getForEntity("http://HELLO-SERVICE/po?name={1}", User.class, "liukaizhao").getBody() ;
        return user.getName() ;
    }

    @RequestMapping(value = "/ribbon-param", method = RequestMethod.GET)
    public String ribbonParam(){
        Map<String,String> param = new HashMap<>() ;
        param.put("name", "liukaizhao") ;
        return restTemplate.getForEntity("http://HELLO-SERVICE/user?name={name}",String.class, param).getBody() ;
    }

    @RequestMapping(value = "/ribbon-uri", method = RequestMethod.GET)
    public String ribbonUri(){
        UriComponents uriComponents = UriComponentsBuilder.fromUriString(
                "http://HELLO-SERVICE/user?name={name}")
                .build()
                .expand("dodo")
                .encode() ;
        URI uri = uriComponents.toUri() ;
        return restTemplate.getForEntity(uri,String.class).getBody() ;
    }

    /**************** getForObject 系列方法 同getForEntity大体相似 ***************/
    @RequestMapping(value = "/ribbon-username01", method = RequestMethod.GET)
    public String ribbonUsername01(){
        return restTemplate.getForObject("http://HELLO-SERVICE/user?name={1}", String.class, "liukaizhao") ;
    }

    /***************** post方法 ******************/
    @RequestMapping(value = "/ribbon-username02", method = RequestMethod.GET)
    public String ribbonUserName02(){
        User user = new User("liukaizhao", 30) ;
        return restTemplate.postForEntity("htpp://HELLO-SERVICE/puser", user, String.class).getBody() ;
    }

}
